<template>
  <div>
        <div class="ele-table-tool ele-table-tool-default">
        <el-button @click="showAddStudentForm=true" type="primary" icon="el-icon-plus" class="ele-btn-icon" size="small">新建宿舍楼</el-button>
        <el-button @click="remove()" type="danger" icon="el-icon-delete" class="ele-btn-icon" size="small">批量删除</el-button>
        <el-button @click="showCreateDataImportForm=true" type="primary" icon="el-icon-plus" class="ele-btn-icon" size="small">导入</el-button>
        <el-button @click="showDataExportForm=true" type="primary" icon="el-icon-minus" class="ele-btn-icon" size="small">导出</el-button>
      </div>
      <!-- 数据表格 -->
 <el-table
    ref="multipleTable"
    :data="data"
    tooltip-effect="dark"
    height="calc(100vh - 265px)" highlight-current-row
    style="width: 100%"
    @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="45" align="center" fixed="left"/>
          <el-table-column type="index" label="编号" width="60" align="center" fixed="left" show-overflow-tooltip/>
          <el-table-column prop="name" label="楼层名称"  show-overflow-tooltip min-width="120"/>                            
          <el-table-column prop="room_num" label="宿舍数"  show-overflow-tooltip min-width="80"/>
          <el-table-column prop="person_num" label="住宿人员数"  show-overflow-tooltip min-width="120"/>
          <el-table-column prop="duty_id" label="负责人及职责"  show-overflow-tooltip min-width="120"/>
          <el-table-column prop="mark" label=" 备注"  show-overflow-tooltip min-width="120"/>
          <el-table-column label="操作" width="200px" align="center" :resizable="false"  fixed="right">
      <template slot-scope="scope">
        <el-button
          size="mini"
          @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
        <el-button
          size="mini"
          type="danger"
          @click="handleDelete(scope.$index, scope.row)">删除</el-button>
      </template>
          </el-table-column>
  </el-table>
      <el-pagination
       :current-page="requestData.page.current_page" :page-size="requestData.page.per_page" :total="requestData.page.total"
        :background="true" layout="total, sizes, prev, pager, next, jumper" :page-sizes="[10,20,50,100, 200,]"
        prev-text="上一页" next-text="下一页" 
        @size-change="pageSizeChange" @current-change="pageCurrentChange" class="ele-pagination-circle"/>
  </div>
</template>

<script>
// import AddStudent from './create';
// import CreateDataImport from './create-data-import';
// import UpdateDataImport from './update-data-import';
// import BatchBindCard from './batch-bind-card';
// import DataExport from './data-export';
export default {
  name: "DormBuilding",
  // components: {AddStudent, CreateDataImport, DataExport, UpdateDataImport, BatchBindCard},
  data() {
    return {
      choose: [],  // 表格选中数据
      showEdit: false,  // 是否显示表单弹窗
      showAddStudentForm: false, // 是否显示创建学生表单弹窗
      showCreateDataImportForm: false, // 是否显示创建数据导入弹窗
      showDataExportForm: false, // 是否显示数据导出弹窗
      showUpdateDataImportForm: false, // 是否显示更新数据导入弹窗
      showBatchBindCardForm: false, // 是否显示批量绑卡弹窗
      editForm: {},  // 表单数据
      searchForm: {}, // 搜索表单
      data:[],
      requestData: {
        where:{},
        page:{
          current_page:1,
          per_page:10
        },
        table:'DormFloor'
      },  // 搜索条件
      queryInfo:{
        url:'/Common/getList'
      }
    }
  },
  mounted() {
    // this.query()
  },
  methods: {
    handleSelectionChange(){},
    nextText(){
      this.requestData.page.current_page--
      this.query()
    },
    prevText(){
      this.requestData.page.per_page++
      this.query()
    },
    pageSizeChange(value){
      this.requestData.page.per_page = value
      this.query()
    },
    pageCurrentChange(value){
      this.requestData.page.current_page = value
      this.query()
    },
    /* 查询 */
    query(level,p_id) {
      this.loading = true;
      this.requestData.where.p_id = p_id
      this.$http.post(this.queryInfo.url, this.requestData).then(res => {
        this.loading = false;
        this.data = res.data.data
        delete res.data.data
        this.requestData.page = {...res.data}
        console.log(this.where)
      }).catch(e => {
        this.loading = false;
        this.$message.error(e.message);
      });
    },
    /* 显示添加 */
    add(row) {
      this.createClassForm = {grade_id: row ? row.id.split('-')[1] : null, grade_name: row ? row.name : null, dynamicItem: []};
      this.showEdit = true;
    },
    /**
     * 显示编辑
     */
    edit(row) {

      if(row.type === 0) { // 为年级
        this.grade_id_for = parseInt(row.id.split('-')[1]);
        this.showCreateGradeForm = true;
      } else {
        this.$http.get('/classes/info?id=' + row.id).then(res => {
          if (res.data.code === 200) {
            this.createClassForm = res.data.result; // https://www.jianshu.com/p/64fdafc983d2
            this.createClassForm.dynamicItem = []; // TODO 需要完善
            this.showEdit = true;
          } else {
            this.$message.error(res.data.msg);
          }
        }).catch(e => {
          this.$message.error(e.message);
        });
      }
    },
    /**
     * 保存编辑
     */
    save() {
      this.$refs['editClassForm'].validate((valid) => {
        if (valid) {
          const loading = this.$loading({lock: true});
          this.$http.post('/classes/edit', this.createClassForm).then(res => {
            loading.close();
            if (res.data.code === 200) {
              this.showEdit = false;
              this.$message({type: 'success', message: res.data.msg});
              this.query();
            } else {
              this.$message.error(res.data.msg);
            }
          }).catch(e => {
            loading.close();
            this.$message.error(e.message);
          });
        } else {
          return false;
        }
      });
    },
    /**
     * 刪除(批量刪除)
     */
    remove(row) {
      console.log(row)
      if (!row) {  // 批量删除
        if (this.choose.length === 0) return this.$message.error('请至少选择一条数据');
        let ids = this.choose.map(d => d.id);
        // TODO 需要区分年级和班级分别进行删除
        this.$confirm('确定要删除选中的班级吗?', '提示', {type: 'warning'}).then(() => {
          const loading = this.$loading({lock: true});
          this.$http.post('/classes/delete', {id: ids}).then(res => {
            loading.close();
            if (res.data.code === 200) {
              this.$message({type: 'success', message: res.data.msg});
              this.query();
            } else {
              this.$message.error(res.data.msg);
            }
          }).catch(e => {
            loading.close();
            this.$message.error(e.message);
          });
        }).catch(() => 0);
      } else {  // 单个删除
        const loading = this.$loading({lock: true});

        if(row.type === 0) { // 为年级
          this.$http.post('/grade/delete', {id:row.id.split('-')[1]}).then(res => {
            loading.close();
            if (res.data.code === 200) {
              this.$message({type: 'success', message: res.data.msg});
              this.query();
            } else {
              this.$message.error(res.data.msg);
            }
          }).catch(e => {
            loading.close();
            this.$message.error(e.message);
          });
        } else {
          this.$http.post('/classes/delete', {id:row.id}).then(res => {
            loading.close();
            if (res.data.code === 200) {
              this.$message({type: 'success', message: res.data.msg});
              this.query();
            } else {
              this.$message.error(res.data.msg);
            }
          }).catch(e => {
            loading.close();
            this.$message.error(e.message);
          });
        }
      }
    },
    addItem () {
      this.createClassForm.dynamicItem.push({
        worker_id: '',
        duty_code: '',
        subject_code: '',
        key: Date.now(),
      })
      this.$forceUpdate();
    },
    deleteItem (item, index) {
      this.createClassForm.dynamicItem.splice(index, 1)
    },
    /**
     * 清理查询表单
     */
    clearForm() {
      this.where = {};
    },
    /**
     * 获取所有教职工
     */
    getWorkers() {
      this.$http.get('/worker/getWorkersIdName').then(res => {
        this.loading = false;
        if (res.data.code === 200) {
          this.workers = res.data.result;
        } else {
          this.$message.error(res.data.msg || '获取数据失败');
        }
      }).catch(e => {
        this.$message.error(e.message);
      });
    },
    /**
     * 获取教职工角色 TODO 应该从角色表中获取
     */
    getDutys() {
      this.$http.get('/dictType/class_duty_code').then(res => {
        this.loading = false;
        if (res.data.code === 200) {
          this.dutys = res.data.result;
        } else {
          this.$message.error(res.data.msg || '获取数据失败');
        }
      }).catch(e => {
        this.$message.error(e.message);
      });
    },
    /**
     * 获取所有科目
     */
    getSubjects() {
      this.$http.get('/dictType/subject_code').then(res => {
        this.loading = false;
        if (res.data.code === 200) {
          this.subjects = res.data.result;
        } else {
          this.$message.error(res.data.msg || '获取数据失败');
        }
      }).catch(e => {
        this.$message.error(e.message);
      });
    },
    /**
     * 对话框弹出时回调方法
     */
    dialogOpen() {
      this.getWorkers();
      this.getDutys();
      this.getSubjects();
    },
    changeClassName(value) {
      this.createClassForm.name = this.createClassForm.grade_name + '('+ value + ')班'
    }
  }                                                       }
</script>

<style scoped>
.ele-block >>> .el-upload, .ele-block >>> .el-upload-dragger {
  width: 100%;
}
</style>